
from rest_framework import serializers

from . import models

class OrderModelSerializer(serializers.ModelSerializer):

    ids = serializers.ListField(child=serializers.IntegerField())

    class Meta:
        model = models.Order
        fields = [
            'ids',
            'subject',
            'total_amount',
        ]

    def validate(self, attrs):
        ids = attrs.pop('ids')
        total_amount = attrs.get('total_amount')

        if not ids:
            raise serializers.ValidationError({'ids': '未传递商品主键'})
        course_obj_query = models.Course.objects.filter(pk__in=ids)
        attrs['course_query'] = course_obj_query
        count_price = self.count_price(course_obj_query)
        if count_price != total_amount:
            raise serializers.ValidationError({'total_amount': '商品价格错误'})
        return attrs

    def count_price(self, course_obj_query)->int:
        count = 0
        for course in course_obj_query:
            count += course.price
        return count

